import React from 'react'
import BaseComponent from 'basecomponent'
import icons from 'icons'
import Button from "button";
import './style.scss'
import AntTable from 'anttable'
import {Pagination} from 'antd';
import store from 'store'
import api from 'apis'
import {grideType, gradeType} from 'utils/staticType'
import UploadMusicModal from 'uploadMusicModal'
import moment from 'moment'
import appConfig from 'config'
import auth from 'auth'
import Dropzone from 'react-dropzone';

class Quality extends BaseComponent {
  constructor() {
    super(...arguments);
    const location = this.props.location;
    this.state = {
      qualityData: {
        Id: location.query.Id ?  parseInt(location.query.Id): null,
        Name: '',
        Image: '',
        Institute: {Id: location.state ? location.state.cid : null},
        University: {Id: location.state ? location.state.uid : null},
        Introduce: '',
        Grade: null,
        Timestamp: 0,
        Music: {
          Id: null,
        }
      },
      from: location.state ? location.state.from : '',
      isRevise: location.state ? location.state.revise : false,
      page: 1,
      commentList: [],
      paginationCommentList: [],
      musicData: [{
        Id: null,
        Name: '添加',
        PlayTimes: null,
        Duration: null,
        updateTime: null
      }],
      showModal:false,
      qualityLogoPreview: ''
    }
    store.set('qualityId', location.query.Id ? location.query.Id : 1)
  }

  componentDidMount() {
    const {qualityData} = this.state
    this.setState({from: this.props.location.state.from})
    if (!(qualityData.Id === -1 || typeof qualityData.Id === 'undefined')) {
      this.getQualityDetail(qualityData.Id)
    }
  }

  getQualityDetail(qid) {
    const{musicData}=this.state
    let id = qid ? qid : store.get('qualityId');
    this.qualityDetailRP && this.qualityDetailRP.request.abort();
    this.qualityDetailRP = api.quality.getQualityDetail(id);
    this.registerRequest(this.qualityDetailRP.request);
    this.qualityDetailRP.promise
      .then((res) => {
        let data = res.Data || []
        if(data.Music){
          musicData[0] = data.Music
          data.Music.Id && this.getCommentList(data.Music.Id)
        }
        this.setState({qualityData: data, musicData:musicData});
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  getCommentList(id){
    this.CommentListRP && this.CommentListRP.request.abort();
    this.CommentListRP = api.music.getCommentList(id);
    this.registerRequest(this.CommentListRP.request);
    this.CommentListRP.promise
      .then((res)=>{
        let data = res.Data||[]
        this.setState({commentList: data, paginationCommentList: data.slice(0, 5)});
      })
      .catch((err)=>{
        alert(err.msg)
      })
  }

  handleSubmit() {
    const {qualityData, musicData} = this.state;
    let merginQualityData = Object.assign({},qualityData,{Music:{Id:musicData[0].Id}})
    if(musicData && musicData[0] && musicData[0].Id){
      this.submitData(merginQualityData)
    }else {
      alert('请先添加内容音频')
    }
  }

  submitData(qualityData) {
    if(qualityData.Institute && !qualityData.Institute.Id){
      delete qualityData.Institute
    }
    if (!(qualityData.Id === -1 || typeof qualityData.Id === 'undefined')) {
      this.RQualityRp && this.RQualityRp.request.abort();
      this.RQualityRp = api.quality.reviseQuality(qualityData.Id , qualityData);
      this.registerRequest(this.RQualityRp.request);
      this.RQualityRp.promise
        .then((res) => {
          res.Data&&this.setState({qualityData:res.Data},this.getQualityDetail(res.Data.Id))
          alert('修改成功')
        })
        .catch((err)=>{
          alert(err.msg)
        })
    }else{
      this.AQualityRp && this.AQualityRp.request.abort();
      this.AQualityRp = api.quality.addQuality(qualityData);
      this.registerRequest(this.AQualityRp.request);
      this.AQualityRp.promise
        .then((res) => {
          res.Data&&this.setState({qualityData:res.Data},this.getQualityDetail(res.Data.Id))
          alert('添加成功')
        })
        .catch((err)=>{
          alert(err.msg)
        })
    }
  }

  handlePaginationChange(page) {
    const {commentList} = this.state;
    this.setState({page: page, paginationCommentList: commentList.slice((page - 1) * 5, page * 5)})
  }

  handleMusicView(musicView) {
    const {musicData,qualityData} = this.state
    musicData[0].Id = musicView.Id
    musicData[0].Name = musicView.Name
    musicData[0].updateTime = moment(new Date()).format('YYYY.MM.DD hh:mm')
    let reviseQuality = Object.assign({},qualityData,{Music:{Id:musicView.Id}})
    this.setState({musicData: musicData})
    this.submitData(reviseQuality)
  }

  handleLogoFileSelect(files) {
    const {qualityData} = this.state
    let file = files[0];
    if (file) {
      this.uploadLogoRP && this.uploadLogoRP.request.abort();
      this.uploadLogoRP = api.file.uploadFile(file);
      this.registerRequest(this.uploadLogoRP.request);
      this.uploadLogoRP.promise
        .then((res) => {
          this.setState({
            qualityLogoImg: res.Data || '', qualityData: Object.assign({},
              qualityData, {Image: res.Data || ''})
          });
        })
        .catch((err) => {
          alert(err.msg)
        })
    }
  }

  getLogoImgDiv() {
    const {qualityData, qualityLogoPreview} = this.state
    if (qualityLogoPreview && qualityLogoPreview.length > 0) {
      return <img className={'preview-img'} src={qualityLogoPreview}/>
    } else {
      if (qualityData.Image && qualityData.Image.length > 0) {
        return <img className={'preview-img'}
                    src={`${appConfig.apiHost}/File/?pid=${qualityData.Image}&key=${auth.getFileToken()}`}/>
      } else {
        return <div className={'default-wrapper'}>
          <img className={'image-default'} src={icons.uploadImg}/>
          <span>点击添加LOGO</span>
        </div>
      }
    }
  }
  render() {
    const {qualityData, page, commentList, paginationCommentList,showModal
      ,musicData} = this.state;
    const voiceColumns = [{
      title: '编号',
      dataIndex: 'Id',
      key: 'Id',
    }, {
      title: '专业名称',
      dataIndex: 'Name',
      key: 'Name',
    }, {
      title: '播放量',
      dataIndex: 'PlayTimes',
      key: 'PlayTimes',
    }, {
      title: '时长',
      dataIndex: 'Duration',
      key: 'Duration',
    }, {
      title: '上传时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
             <a onClick={() => {
               this.setState({showModal:true})
             }}>上传</a>
            <span className="ant-divider"/>
          <a href={`${appConfig.apiHost}/File/?pid=${text.Url}&key=${auth.getFileToken()}`}
             download={`${text.Name}.mp3`}>
            下载
          </a>
            <span className="ant-divider"/>
          <a onClick={() => {
            console.log('text',text)
          }}>删除</a>
        </span>
        ),
      }
    ];
    const voiceRowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
      }),
    };
    return (
      <div className={'sem-main-content'}>
        <div className={'major-button-wrapper'}>
          <Button className={'back-button'} onClick={() => {
            this.props.router.goBack()
          }}>{Button.AddOn({
            src: icons.backIcon, style: {
              width: '1rem',
              height: '1rem',
              display: 'block',
              backgroundRepeat: 'no-repeat',
            }
          })}</Button>
          <div className={'add-name'}>
            修改付费内容
          </div>
          <Button className={'save-btn'} onClick={this.handleSubmit.bind(this)}>保存</Button>
        </div>
        <Dropzone className={'image-drop-zone'}
                  onDrop={this.handleLogoFileSelect.bind(this)}
                  accept={'image/*'}
                  multiple={false}>
          {this.getLogoImgDiv()}
        </Dropzone>
        <div className={'major-top-div'}>
          <div className={'option-wrapper'}>
            <div className={'option-title'}>内容名称</div>
            <input className={'option-input'} type={'text'} value={qualityData.Name}
                   onChange={(e) => {
                     this.setState({qualityData: Object.assign(qualityData, {Name: e.target.value})})
                   }}
            />
          </div>
          <div className={'option-wrapper'}>
            <div className={'option-title'}>内容价格</div>
            <input className={'option-input'} type={'number'} value={qualityData.Price}
                   onChange={(e) => {
                     this.setState({qualityData: Object.assign(qualityData, {Price: e.target.value})})
                   }}
            />
          </div>
        </div>

        <div className={'major-middle-div'}>
          <div className={'title-wrapper'}>
            <span className={'title-bar'}/>
            <span className={'title-text'}>内容简介</span>
          </div>
          <textarea className={'work-intro'} value={qualityData.Introduce}
                    onChange={(e) => {
                      this.setState({qualityData: Object.assign(qualityData,{Introduce: e.target.value})})
                    }}/>
        </div>

        <div className={'major-middle-div voice'}>
          <div className={'title-wrapper'}>
            <span className={'title-bar'}/>
            <span className={'title-text'}>内容视频</span>
          </div>
          <AntTable columns={voiceColumns} data={musicData} rowSelection={voiceRowSelection} pagenation={false}/>
        </div>

        <div className={'major-end-div'}>
          <div className={'title-wrapper'}>
            <span className={'title-bar'}/>
            <span className={'title-text'}>内容评论</span>
          </div>
          <ul className={'comment-ul'}>
            {
              paginationCommentList.map((item) => {
                return <li className={'comment-li'} key={item.Id}>
                  <img className={'li-header'} src={`${appConfig.apiHost}/File/?pid=${item.User.Image}&key=${auth.getFileToken()}`}/>
                  <div className={'li-body'}>
                    <span className={'nickname'}>{item.User.Name}</span>
                    <span className={'content'}>{item.Content}</span>
                  </div>
                  <span className={'li-time'}>{moment(new Date(item.UpdateTime)).format('YYYY-MM-DD HH:mm')}</span>
                </li>
              })
            }
          </ul>
          <Pagination defaultCurrent={page}
                      current={page}
                      pageSize={5}
                      total={commentList.length}
                      showTotal={(total, range) => `共${total}条记录，每页5条记录，当前显示第${page}页`}
                      onChange={this.handlePaginationChange.bind(this)}/>
        </div>
        {showModal && <UploadMusicModal handleSave={(musicView)=>{this.handleMusicView(musicView)}}
                                        hideModal={()=>{this.setState({showModal:false})}}/>}
      </div>
    );
  }
}

module.exports = Quality;
